package Learning;


import edu.upf.grupE.Entities.Album;
import edu.upf.grupE.Entities.Picture;
import java.io.StringReader;
import java.util.*;               
import org.exolab.castor.xml.Unmarshaller;
import org.xmldb.api.base.*;
import org.xmldb.api.base.Collection;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;


/**
 *
 * @author Madhava Carrillo <madhava at me.com>
 */
public class UsingPhotoHandler {
	
    /**
     *
     * @param args
     * @throws java.lang.Exception
     */
    public static void main(String[] args) throws Exception {
	
	// Here we will store the Photo objects
	Map<String, Photo> photos = new HashMap<String, Photo>();	    

	// Initialize the driver of the database
	String driver = "org.exist.xmldb.DatabaseImpl";
        String URI = "xmldb:exist://localhost:8088/xmlrpc/db";
        Class cl = Class.forName(driver);			
        Database database = (Database)cl.newInstance();
        DatabaseManager.registerDatabase(database);

	// Obtain the collection and launch the query, obtaining a set o results. 	    
        Collection col = DatabaseManager.getCollection(URI);
        XQueryService service = (XQueryService) col.getService("XQueryService", "1.0");

	ResourceSet result = service.query("//Pictures/Picture");
	    
	// Iterate through the set of results, which are XML elements of type photo 
	// (note that the resources are taken as XMLResources!). 
	// Each XMLResource is processed by the SAX handler (we provide the handler 
	// with a new Photo object so it can store the parsed information).
	// The obtained objects are stored in the HashMap photos. 
	ResourceIterator i = result.getIterator();
	while(i.hasMoreResources()) {

	        XMLResource r = (XMLResource) i.nextResource();
            String idQuery = "Picture.jander";
            //System.out.println((String)r.getContent());
            try {
                Object tmp = Class.forName("edu.upf.grupE.Entities."+idQuery.substring(0, idQuery.indexOf("."))).newInstance();
                tmp = Unmarshaller.unmarshal(tmp.getClass(), new StringReader((String) r.getContent()));
                Picture pic = (Picture) tmp;
                System.out.println(pic.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            
        }
	
	// Print the photo objects we have obtained
	List<String> phs = new ArrayList<String>(photos.keySet());
	Collections.sort(phs);
	for(Iterator iterator = phs.iterator(); iterator.hasNext();) {
	    String id = (String)iterator.next();
	    System.out.println(photos.get(id));
	}
	    
    }
}
